using aichat.Entities;
using aichat.Services;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Regions;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Windows;

namespace aichat.ViewModels
{
    public class ChatViewModel : BindableBase, INavigationAware
    {
        private readonly IChatService _chatService;
        private readonly IUserService _userService;
        private int _currentUserId;

        public ChatViewModel(IChatService chatService, IUserService userService)
        {
            _chatService = chatService;
            _userService = userService;

            SendMessageCommand = new DelegateCommand(SendMessage, CanSendMessage);
            ClearChatCommand = new DelegateCommand(ClearChat);
            LoadChatHistoryCommand = new DelegateCommand(LoadChatHistory);

            ChatMessages = new ObservableCollection<ChatMessage>();
            AvailableModels = new ObservableCollection<AiModel>();
        }

        public void OnNavigatedTo(NavigationContext navigationContext)
        {
            if (navigationContext.Parameters.ContainsKey("CurrentUserId"))
            {
                _currentUserId = navigationContext.Parameters.GetValue<int>("CurrentUserId");
                LoadAvailableModels();
                LoadChatHistory();
            }
        }

        public bool IsNavigationTarget(NavigationContext navigationContext)
        {
            return true;
        }

        public void OnNavigatedFrom(NavigationContext navigationContext)
        {
            // 清理资源
        }

        private string _userInput = string.Empty;
        public string UserInput
        {
            get => _userInput;
            set
            {
                SetProperty(ref _userInput, value);
                SendMessageCommand.RaiseCanExecuteChanged();
            }
        }

        private string _aiResponse = string.Empty;
        public string AiResponse
        {
            get => _aiResponse;
            set => SetProperty(ref _aiResponse, value);
        }

        private AiModel _selectedModel = null!;
        public AiModel SelectedModel
        {
            get => _selectedModel;
            set => SetProperty(ref _selectedModel, value);
        }

        private bool _isTyping = false;
        public bool IsTyping
        {
            get => _isTyping;
            set => SetProperty(ref _isTyping, value);
        }

        public ObservableCollection<ChatMessage> ChatMessages { get; }
        public ObservableCollection<AiModel> AvailableModels { get; }

        public DelegateCommand SendMessageCommand { get; }
        public DelegateCommand ClearChatCommand { get; }
        public DelegateCommand LoadChatHistoryCommand { get; }

        // 添加事件通知属性变化
        public event EventHandler? ScrollToBottomRequested;

        private void RequestScrollToBottom()
        {
            ScrollToBottomRequested?.Invoke(this, EventArgs.Empty);
        }

        private async void SendMessage()
        {
            if (string.IsNullOrWhiteSpace(UserInput) || SelectedModel == null)
                return;

            try
            {
                IsTyping = true;

                // 先创建用户消息（不包含AI响应）
                var userMessage = new ChatMessage
                {
                    UserId = _currentUserId,
                    UserMessage = UserInput,
                    AiResponse = "", // 先设为空
                    AiModel = SelectedModel.Name,
                    CreatedAt = DateTime.Now,
                };

                // 添加用户消息到列表末尾
                ChatMessages.Add(userMessage);
                
                // 请求滚动到底部
                RequestScrollToBottom();

                // 清空输入框
                var currentInput = UserInput;
                UserInput = string.Empty;

                // 显示打字机效果 - 通过Progress回调实时更新AiResponse
                var progress = new Progress<string>(text => 
                {
                    userMessage.AiResponse = text; // 实时更新消息内容，会触发UI更新
                });

                var aiResponse = await _chatService.GetTypingResponseAsync(
                    currentInput, 
                    SelectedModel.Name, 
                    progress);

                // 更新最终响应和统计信息
                userMessage.AiResponse = aiResponse;
                userMessage.TokensUsed = EstimateTokens(currentInput + aiResponse);
                userMessage.IsSuccessful = true;

                // 保存到数据库
                await _chatService.SaveChatMessageAsync(userMessage);

                // 增加用户聊天次数
                await _userService.IncrementChatCountAsync(_currentUserId);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发送消息失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                IsTyping = false;
            }
        }

        private int EstimateTokens(string text)
        {
            // 简单的token估算：大约4个字符=1个token
            return Math.Max(1, text.Length / 4);
        }

        private bool CanSendMessage()
        {
            return !string.IsNullOrWhiteSpace(UserInput) && 
                   SelectedModel != null && 
                   !IsTyping;
        }

        private void ClearChat()
        {
            ChatMessages.Clear();
            AiResponse = string.Empty;
        }

        private async void LoadChatHistory()
        {
            try
            {
                var history = await _chatService.GetUserChatHistoryAsync(_currentUserId);
                
                ChatMessages.Clear();
                foreach (var message in history)
                {
                    ChatMessages.Add(message);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载聊天历史失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void LoadAvailableModels()
        {
            try
            {
                var models = await _chatService.GetAvailableAiModelsAsync(_currentUserId);
                
                AvailableModels.Clear();
                foreach (var model in models)
                {
                    AvailableModels.Add(model);
                }

                if (AvailableModels.Count > 0)
                {
                    SelectedModel = AvailableModels[0];
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载AI模型失败: {ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
} 